package com.jet.rtdb.socket.server;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.jet.rtdb.common.utils.MessageConstant;
import com.jet.rtdb.pojo.QueryHistoryDataList;
import com.jet.rtdb.pojo.QueryLastDataList;
import com.jet.rtdb.service.RtdbService;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;

/**
 * @Author: zhangkaifeng.
 * @CreateTime: 2017/8/17 14:59
 * @Description:
 */
@Component
@Qualifier("rtdbServerHandler")
@ChannelHandler.Sharable
public class RtdbServerHandler extends ChannelInboundHandlerAdapter {

    @Autowired
    RtdbService rtdbService;

    private static final Logger logger = LoggerFactory.getLogger(RtdbServerHandler.class);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {

        try {
            if (msg instanceof QueryLastDataList) {
                QueryLastDataList queryLastDatas = (QueryLastDataList) msg;
                queryLastDatas = rtdbService.getLastData(queryLastDatas);
                GsonBuilder gsonbuilder = new GsonBuilder().serializeNulls();
                Gson gson = gsonbuilder.create();
                String string = gson.toJson(queryLastDatas);
                byte[] bytes = string.getBytes(Charset.forName("UTF-8"));
                ByteBuf byteBuf = ctx.alloc().buffer();
                byteBuf.writeByte(MessageConstant.GET_POINT_LAST_DATA);
                byteBuf.writeInt(bytes.length);
                byteBuf.writeBytes(bytes);
                ctx.write(byteBuf);
                ctx.flush();
            } else if (msg instanceof QueryHistoryDataList) {
                QueryHistoryDataList queryHistoryDataList = (QueryHistoryDataList) msg;
                queryHistoryDataList = rtdbService.getHistoryData(queryHistoryDataList);
                GsonBuilder gsonbuilder = new GsonBuilder().serializeNulls();
                Gson gson = gsonbuilder.create();
                String string = gson.toJson(queryHistoryDataList);
                byte[] bytes = string.getBytes(Charset.forName("UTF-8"));
                ByteBuf byteBuf = ctx.alloc().buffer();
                byteBuf.writeByte(MessageConstant.GET_POINT_HIS_DATA);
                byteBuf.writeInt(bytes.length);
                byteBuf.writeBytes(bytes);
                ctx.write(byteBuf);
                ctx.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ReferenceCountUtil.release(msg);
        }

    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("新连入的客户端:{}", ctx.channel().remoteAddress().toString());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // Close the connection when an exception is raised.
        cause.printStackTrace();
        ctx.close();
    }

}
